import functools
import time

from core.logger import root_logger


# 装饰器，http重试
def http_retry(max_retries=3, retry_delay=1, offset=0):
    max_retries = 1 if max_retries <= 0 else max_retries

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            retries = 0
            while retries <= max_retries:
                try:
                    result = func(*args, **kwargs)
                    return result
                except Exception as e:
                    root_logger.error(f"请求失败：{e}")
                    retries += 1
                    if retries < max_retries:
                        sleep_time = retry_delay + retries * offset
                        root_logger.error(f"等待 {sleep_time} 秒后进行第 {retries + 1} 次重试...")
                        time.sleep(sleep_time)
                    else:
                        root_logger.error(f"请求失败，已达到最大重试次数 {max_retries} 次，放弃重试。")
                        return None

        return wrapper

    return decorator


# 装饰器，单例
def singleton(cls):
    instances = {}

    def wrapper(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return wrapper
